﻿using System;
using System.Windows.Data;
using System.Windows.Markup;

// A collection of value converter classes for use in XAML.

// For some unknown reasons the WPF FormatConverter didn't work as expected,
// therefore the string converter was written, with the good news, that it
// does respect culture settings as opposed to the WPF converter when used
// for example with DateTime values.

namespace ScreenMonkey.Remote
{
    
    /// <summary>
    /// Class to simplify the usage of ValueConverters.
    /// If you want to use a normal ValueConverter in XAML, you have to add an instance of it
    /// to the resources and reference it by using a key.
    /// By derivating value converters from MarkupExtension, you can create and use it in the
    /// binding like this: Text={Binding Time, Converter={x:StringFormatConverter}}.
    ///
    /// It's the same class as used in the CeetGui, just copied over here.
    /// Thus it should become part of a common library in the future.
    /// </summary>
    public abstract class BaseConverter : MarkupExtension
    {
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }

    [ValueConversion(typeof(object), typeof(string))]
    public class StringFormatConverter : BaseConverter, IValueConverter
    {
        public StringFormatConverter()
        {
            // Empty constructor to humor the XAML compiler
        }

        public object Convert(object value, Type targetType, object parameter,
                              System.Globalization.CultureInfo culture)
        {
            string format = parameter as string;

            if (!string.IsNullOrEmpty(format))
            {
                return string.Format(culture, format, value);
            }
            else
            {
                return value.ToString();
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter,
                                  System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}
